package com.yxhl.zoume.core.car.fragment.common;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.custom.QuickIndexBar;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.specialcar.model.CarLocationMapEntrance;
import com.yxhl.zoume.core.car.model.SelectCityEntity;
import com.yxhl.zoume.core.car.presenter.AlphabetSearchPresenter;
import com.yxhl.zoume.core.car.presenter.SelectCityPresenter;
import com.yxhl.zoume.core.car.adapter.SelectCityAdapter;
import com.yxhl.zoume.core.car.model.SelectCityEvent;
import com.yxhl.zoume.core.car.view.common.AlphabetSearchView;
import com.yxhl.zoume.core.car.view.common.SelectCityView;
import com.yxhl.zoume.di.component.car.DaggerOfficialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.LOG;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * 项目名称：Ferrari
 * Created by menggod on 2016/9/2.
 */
public class SelectCityFragment extends BaseFragment implements AlphabetSearchView<SelectCityEntity>, SelectCityView {

    private static final String TAG = "SelectCityAdapter";
    @BindView(R.id.rv_select_city)
    RecyclerView mCityRecycleView;
    @BindView(R.id.tv_center_index)
    TextView mCenterIndex;
    @BindView(R.id.qib)
    QuickIndexBar mIndexBar;
    @Inject
    AlphabetSearchPresenter<SelectCityEntity> mAlphabetSearchPresenter;
    @Inject
    SelectCityPresenter mSelectCityPresenter;
    private CarLocationMapEntrance mEntrance;
    private List<SelectCityEntity> mCitylist = new ArrayList<>();
    private SelectCityAdapter mSelectCityAdapter;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mCitylist = (List<SelectCityEntity>) msg.obj;
                    mSelectCityAdapter.setCityEntityList(mCitylist);
                    LOG.v(TAG, "mCitylist size = " + mCitylist.size());
                    mSelectCityAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    public static SelectCityFragment newInstance(CarLocationMapEntrance entrance) {
        SelectCityFragment fragment = new SelectCityFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(UIConstants.Car.ARGUMENT_KEY_SPECIAL_CAR_CITY_PARAM, entrance);
        fragment.setArguments(bundle);
        return fragment;
    }


    /**
     * 条目点击finfish
     */
    private void onRxBusEvent() {
        getSubscription().add(toSubscription(SelectCityEvent.class,
                new Action1<SelectCityEvent>() {
                    @Override
                    public void call(final SelectCityEvent selectCityEvent) {
                        getActivity().onBackPressed();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onRxBusEvent();
        parseArguments();
        mSelectCityPresenter.copyFile();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mAlphabetSearchPresenter.attachView(this);
        mSelectCityPresenter.attachView(this);
        ButterKnife.bind(this, view);
        initializeRecyclerView();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initCityList();
        mIndexBar.setOnIndexChangeListener(new MyOnIndexChangeListener());

    }

    private void parseArguments() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mEntrance = (CarLocationMapEntrance) arguments.getSerializable(UIConstants.Car.ARGUMENT_KEY_SPECIAL_CAR_CITY_PARAM);
        }
    }

    public void setEntrance(CarLocationMapEntrance entrance) {
        mEntrance = entrance;
    }

    private void initCityList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mSelectCityPresenter.readDatabases();
            }
        }).start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    private void initializeRecyclerView() {

        mSelectCityAdapter = new SelectCityAdapter(
                mActivity,
                mCitylist
        );

        mCityRecycleView.setAdapter(mSelectCityAdapter);
        mCityRecycleView.setLayoutManager(new LinearLayoutManager(mActivity));
//        mCityRecycleView.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f)));
    }

    @Override
    protected void initializeInjector() {
        DaggerOfficialCarComponent
                .builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_common_select_city;
    }

    @Override
    protected void setupToolBar() {

    }

    @Override
    public void renderAlphabetSearchResult(List<SelectCityEntity> searchEntityList) {

    }

    @Override
    public void renderSelectCity(List<SelectCityEntity> list) {
        mAlphabetSearchPresenter.setSearchEntityList(list);
        Message message = Message.obtain();
        message.what = 1;
        message.obj = list;
        mHandler.sendMessage(message);

    }

    private class MyOnIndexChangeListener implements QuickIndexBar.OnIndexChangeListener {
        @Override
        public void onIndexChange(String selectAlphabet) {
            mCenterIndex.setText(selectAlphabet);
            mCenterIndex.setVisibility(View.VISIBLE);
            int indexOf = mCitylist.indexOf(new SelectCityEntity(selectAlphabet));
            if (indexOf >= 0) {
                if (mCityRecycleView != null) {
                    mCityRecycleView.scrollToPosition(indexOf);
                }
            }
        }

        @Override
        public void onActionUp() {
            mCenterIndex.setVisibility(View.GONE);
        }
    }
}
